package com.hyts.sdkhttp.handler;

import com.alibaba.fastjson.JSONObject;
import com.hyts.sdkhttp.domain.SdkURLConnection;

import java.io.IOException;
import java.io.PrintWriter;

/**
 * project-name:iscloud
 * package-name:com.ultrapower.zq.handler
 * author:Libo/Alex
 * create-date:2018-03-12 10:50
 * copyright:libo-hyts-github
 * email:libo2dev@aliyun.com
 * description:此类主要用于: sdkRequest服务操作处理器句柄
 */
public final class SdkRequestHandler {

	private static final String PARAM_SEP_TOKEN = "&";

	/**
	 * @Title: open
	 * @Description: 打开请求连接
	 * @param @param connection
	 * @param @return    参数
	 * @return HttpURLConnection    返回类型
	 * @throws
	 */
	public static SdkURLConnection open(SdkURLConnection connection){
		try {
			connection.getConnection().connect();
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		return connection;
	}

	/**
	 * @Title: open
	 * @Description: 打开连接传入参数
	 * @param @param connection
	 * @param @param param
	 * @param @return    参数
	 * @return SdkURLConnection    返回类型
	 * @throws
	 */
	public static SdkURLConnection open(SdkURLConnection connection,JSONObject param){
		try(
			PrintWriter writer = new PrintWriter(connection.getConnection().getOutputStream(),true);
			){
			connection.getConnection().connect();
			StringBuilder paramstr = new StringBuilder();
			param.forEach( (key,value) -> {
				paramstr.append(key).append(" = ").append(value).append(PARAM_SEP_TOKEN);
			});
			writer.write(paramstr.delete(0, paramstr.lastIndexOf(PARAM_SEP_TOKEN)).toString());
			writer.flush();
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		return connection;
	}

	/**
	 * @Title: close
	 * @Description: 断开连接
	 * @param @param connection
	 * @param @return    参数
	 * @return HttpURLConnection    返回类型
	 * @throws
	 */
	public static SdkURLConnection close(SdkURLConnection connection){
		try {
			connection.getConnection().disconnect();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return connection;
	}


}
